package com.java80.littlegame.common.db.dao.cacheImpl;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import com.java80.littlegame.common.cache.CacheService;
import com.java80.littlegame.common.db.dao.UUserInfoDao;
import com.java80.littlegame.common.db.dao.dbImpl.UUserInfoDaoDBImpl;
import com.java80.littlegame.common.db.entity.UUserInfo;

public class UUserInfoDaoCacheImpl implements UUserInfoDao {
	private UUserInfoDaoDBImpl rdb;

	public UUserInfoDaoCacheImpl(UUserInfoDaoDBImpl rdb) {
		super();
		this.rdb = rdb;
	}

	@Override
	public List<UUserInfo> getAllByUserId(long userId) {
		UUserInfo uUserInfo = this.get(userId);
		return Arrays.asList(uUserInfo);
	}

	@Override
	public void insert(UUserInfo t) {
		try {
			rdb.insert(t);
			t.save();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void delete(long id) {
		try {
			rdb.delete(id);
			CacheService.remove(CacheService.CACHEOBJPROFIX + this.getClass().getSimpleName() + "-" + id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void update(UUserInfo t) {
		try {
			rdb.update(t);
			t.save();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public UUserInfo get(long id) {
		UUserInfo userInfo = CacheService.get(CacheService.CACHEOBJPROFIX + this.getClass().getSimpleName() + "-" + id,
				UUserInfo.class);
		if (userInfo != null) {
			return userInfo;
		} else {
			try {
				UUserInfo uUserInfo = rdb.get(id);
				return uUserInfo;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;
	}

	@Override
	public UUserInfo login(String userName, String password) {
		try {
			UUserInfo login = rdb.login(userName, password);
			if (login != null) {
				login.save();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public UUserInfo findByLoginName(String loginName) {
		try {
			return rdb.findByLoginName(loginName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}
